<?php
require_once 'Kanedo/Config/Ini.php';
require_once 'Kanedo/Model/Exception.php';
require_once 'Kanedo/Db/Exception.php';
class Module
{
	protected $_path;
	/**
	 * DB
	 *
	 * @var Kanedo_Db
	 */
	protected $_db = null;
	public function __construct(Kanedo_Db $db,$path = "./MODULES/")
	{
		$this->_db = $db;
		$this->_path = $path;
	}
	public function validateModule($name)
	{
		if(!file_exists($this->_path.$name."/config.ini"))
		{
			throw new Kanedo_Model_Exception('no_config_file');
		}
		$config = new Kanedo_Config_Ini($this->_path.$name."/config.ini");
		$config = $config->getSection($name);
		if(!key_exists('outputClassName', $config) || !key_exists('outputClassFile', $config))
		{
			throw new Kanedo_Model_Exception('no_module_config');
		}
		if(!file_exists($this->_path.$name."/".$config['outputClassFile']))
		{
			throw new Kanedo_Model_Exception('no_module_output_class_file');
		}
		require_once $this->_path.$name."/".$config['outputClassFile'];
		if(!class_exists($config['outputClassName']))
		{
			throw new Kanedo_Model_Exception('no_module_output_class_file');	
		}
		$module = new $config['outputClassName'];
		if(!$module instanceof Kanedo_Module_Interface )
		{
			throw new Kanedo_Model_Exception('module_instance_of_interface');
		}
		return $module;
	}
	public function addModuleToLibrary($name)
	{
		$module = $this->validateModule($name);	
		$serializedModule = serialize($module);
		$sql = " INSERT INTO `kanedo_cms`.`model_object` (`id_model_object`, `object`) VALUES (NULL, '".$serializedModule."');";
		$result = $this->_db->executeQuery($sql);
	    if(!$result)
	    {
	    	throw new Kanedo_Db_Exception('invalid_ressource {'.mysql_error($this->_db->getRessource()).'}');
	    }
	    
		$id = mysql_insert_id();
		$sql = "INSERT INTO `model_registered` ( `id_model_registered` , `name` , `path` , `configfile` , `model_object_id_model_object` )
				VALUES (
						NULL , 
						'".$name."', 
						'".$this->_path.$name."', 
						'".$this->_path.$name."/config.ini', 
						".$id.");";
		$result = $this->_db->executeQuery($sql);
		if(!$result)
	    {

	    	throw new Kanedo_Db_Exception('invalid_ressource {'.mysql_error($this->_db->getRessource()).'}');
	    }	
	
	}
	

	public function getAllNonRegisteredModules()
	{
		$ordner = opendir($this->_path);
		$results = array();
		while($datei = readdir($ordner)) {
 				if(is_dir($this->_path.$datei) && $datei != "." && $datei != ".." && substr($datei, 0, 1) != ".")
 				{
 					if(!$this->getModuleFromDatabase($datei))
 					{
 						$results[] = "<a href=\"/admin/module/add/?name=".$datei."\">".$datei." hinzuf&uuml;gen</a>";	
 					}
 					
 				} 
		}
		closedir($ordner);
		return $results;
	}
	

	public function getModuleFromDatabase($name)
	{
		$sql = "SELECT `name` FROM  `model_registered` WHERE `name` = '".$name."'";
		$result = $this->_db->executeQuery($sql);
		if(!$result)
		{
			throw new Kanedo_Db_Exception('invalid_ressource {'.mysql_error($this->_db->getRessource()).'}');
		}
		$tmp = $this->_db->fetchAll($result);
		if(empty($tmp))
		{
			return false;
		}else{
			return $tmp;
		}
	}
	
	public function getModuleById($id)
	{
		$sql = "SELECT * FROM `model_registered` WHERE `id_model_registered` = ".(int)$id;
		$result = $this->_db->executeQuery($sql);
		if(!$result)
		{
			throw new Kanedo_Db_Exception('invalid_ressource {'.mysql_error($this->_db->getRessource()).'}');
		}
		$tmp = $this->_db->fetchAll($result);
		if(empty($tmp))
		{
			throw new Kanedo_Model_Exception('no_module');
		}else{
			return $tmp;
		}
	}
	

	public function remove($name, $files = false)
	{    
		$sql = "SELECT * FROM `model_registered` WHERE `id_model_registered` = '".$name."'";
		$result = $this->_db->executeQuery($sql);
	    if(!$result)
	    {
	    	throw new Kanedo_Db_Exception('invalid_ressource {'.mysql_error($this->_db->getRessource()).'}');
	    }
	    $module = $this->_db->fetchAll($result);
		if($files)
		{
	    	$this->rmdir_recurse($this->_path.$module[0]['name']);
	    	rmdir($this->_path.$module[0]['name']);
		}
		
		$sql = "DELETE FROM `model_registered` WHERE `id_model_registered` = ".$name." LIMIT 1;";
		$result = $this->_db->executeQuery($sql);
	    if(!$result)
	    {
	    	throw new Kanedo_Db_Exception('invalid_ressource {'.mysql_error($this->_db->getRessource()).'}');
	    }
		$sql = "DELETE FROM `model_object` WHERE `id_model_object` = ".$module[0]['model_object_id_model_object']." ;";
		$result = $this->_db->executeQuery($sql);
	    if(!$result)
	    {
	    	throw new Kanedo_Db_Exception('invalid_ressource {'.mysql_error($this->_db->getRessource()).'}');
	    }
	}
	

	protected function rmdir_recurse($path)
	{
	    $path= rtrim($path, '/').'/';    
	    $handle = opendir($path);
	    while(false !== ($file = readdir($handle))) {
	        if($file != "." && $file != ".." )
	        {
	            $fullpath= $path.$file;
	            if( is_dir($fullpath) )
	            {
	                $this->rmdir_recurse($fullpath);
	                rmdir($fullpath);
	            }else{
	              unlink($fullpath);
	            }
	       }
	    }
	    closedir($handle);
	} 
	
	public function getAllRegisteredModules()
	{
		$sql = "SELECT `id_model_registered` , `name` FROM `model_registered`";
		$result = $this->_db->executeQuery($sql);
		if($result)
		{
			return $this->_db->fetchAll($result);
			
		}
	}
	
	public function getModuleImage($id)
	{
		$sql = "SELECT `configfile`, `name` FROM `model_registered` WHERE `id_model_registered` = ".(int)$id;
		$result = $this->_db->executeQuery($sql);
		if($result)
		{
			$data = $this->_db->fetchAll($result);
			
		}else {
			throw new Kanedo_Module_Exception('unknown_model');
		}
		$config = new Kanedo_Config_Ini($data[0]['configfile']);
		if($config->$data[0]['name']->placeHolderImage != "")
		{
			return "/MODULES/".$data[0]['name']."/".$config->$data[0]['name']->placeHolderImage;
		}else {
			throw new Kanedo_Model_Exception('no_image');
		}
	}
	
}
?>